package com.qf.smsplatform.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisTemplateConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        //1. 创建RedisTemplate<String,Object>
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        //2. 连接Redis服务
        redisTemplate.setConnectionFactory(connectionFactory);

        //3. 配置key的序列化
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setHashKeySerializer(keySerializer);

        //4. 配置value的序列化
        Jackson2JsonRedisSerializer valueSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);

        //5. 生效
        redisTemplate.afterPropertiesSet();

        //6. 返回
        return redisTemplate;
    }
//    @ConditionalOnMissingBean   SpringBoot中的自动装配一般都会添加当前注解，
//    目的是可以让用户使用SpringBoot的配置，也可以让用户自己配置时，SpringBoot不去自动装配了。

}
